package com.example.databinding_demo.livedata;

import android.os.Bundle;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.example.databinding_demo.R;
import com.example.databinding_demo.databinding.ActivityMvvmBinding;
import com.example.databinding_demo.databinding.ActivityUserBinding;
import com.example.databinding_demo.mvvm.MvvmViewModel;

public class NameActivity extends AppCompatActivity {

    private UserViewModel userViewModel;
    private TextView nameTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Other code to setup the activity...

        ActivityUserBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_user);

        // Get the ViewModel.
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
        binding.setUserViewModel(userViewModel);
        nameTextView = findViewById(R.id.livedata_tv);
        // Create the observer which updates the UI.
        final Observer<String> nameObserver = new Observer<String>() {
            @Override
            public void onChanged(@Nullable final String newName) {
                // Update the UI, in this case, a TextView.
                nameTextView.setText(newName);
            }
        };

        // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
        userViewModel.getName().observe(this, nameObserver);
    }
}
